﻿using System;
using System.Collections.Generic;
using System.Text;
using DecodeInterface;
using System.Drawing;
using System.Windows.Forms;

namespace MotionDetect
{
    public class BackgroundSubtract : DecodeBitmap
    {
        readonly Size sizeMax = new Size(200, 200);
        readonly Size sizeMin = new Size(20, 20);

        //public BackgroundSubtract() { }
        //public BackgroundSubtract(Control decodeShow) : base(decodeShow) { }

        protected override unsafe object[] OnDecode(byte* pIn, byte* pOut, Size sizeIn, Size sizeOut, params object[] state)
        {
            if (state.Length < 3 || !(state[2] is byte[,]))
                throw new ApplicationException("third object of state is StableBackground|Decode");

            byte[,] StableBackground = state[2] as byte[,];

            #region 运动点标记
            for (int yOut = 0; yOut < sizeOut.Height; yOut++)
            {
                for (int xOut = 0; xOut < sizeOut.Width; xOut++)
                {
                    int index = (yOut * sizeOut.Width + xOut) * 3;
                    pOut[index] =
                    (byte)(Math.Abs(StableBackground[xOut, yOut]
                    - pIn[(yOut * sizeOut.Width + xOut) * 3]) > 50 ? 255 : 0);
                    pOut[index + 1] = pOut[index + 2] = 0;
                }
            }
            #endregion

            ////获取运动点所在区域
            List<Rectangle> rectActive = DataManager.GetExpandRegion(pOut, sizeOut, sizeMin, sizeMax);
            //合并重叠区域
            DataManager.UnionRectangle(ref rectActive, new Size(10, 10));
            //过滤边缘区域
            Rectangle rectLimits = new Rectangle(new Point(), sizeOut);
            rectLimits.Inflate(-50, -50);
            List<Rectangle> rectContain = DataManager.ContainRectangle(rectActive, rectLimits);
            //获取最大区域
            Rectangle rectMax = DataManager.MaxRectangle(rectContain);
            foreach (var rect in rectContain)
            {
                if (rect == rectMax)
                    DataManager.DrawRectangle(rectMax, Color.Red, pOut, sizeOut);
                else
                    DataManager.DrawRectangle(rect, Color.Lime, pOut, sizeOut);
            }

            return new object[] { rectContain, rectMax };
        }
    }
}
